<?php
$i = 1;
$allDicount = 0;
foreach ($this->cart->contents() as $items) :

	$option = $this -> cart -> product_options($items['rowid']);
	$option = (array)$option;
	$pID = $option['MATNR'];
	$pName = $option['MAKTX'];
	$baseUnit = $option['BASE_UNIT'];
	$cartonRatio = $option['EA_CARTON'];
	$packRatio = $option['EA_PACK'];
	$itemPrice = $items['price'];
	if ($baseUnit == "KAR") {
		$b = "ลัง";
	} else if ($baseUnit == "PAK") {
		$b = "แพ็ก";
	} else {
		$b = "ชิ้น";
	}
	$i++;
endforeach;

$p = 0;
$maxPrice = 0;
$promotionID = "";
foreach ($sumOfPromotion as $in => $val) {
	
	if ($val['PRODUCT_IN_PROMOTION'] != false) {
		$desc = $val['PROMO_DESC'];
		$allDicount += $val['DISC_AMT'];
		
		$productList = $val['PRODUCT_IN_PROMOTION'];
		
		$promotionID = $productList[0]->PROMO_ID;
		
		$column = $PRICE_COLUMN;
		$unit = $PRICE_COLUMN_UNIT;

		if ($p == 0) {

			$firstID = $productList[0];

			$price = $firstID -> $column;
			$unit = $firstID -> $unit;

			$s = explode("/", $unit);
			$pricePerUnit = $s[1];
			if ($pricePerUnit == "CAR") {
				$ratio = 1;
			} else if ($pricePerUnit == "PAC") {
				$ratio = $firstID -> EA_CARTON / $firstID -> EA_PACK;
			}
			$itemPrice = ($price * $ratio);
			if ($val['FREE_QTY_KAR'] > 0) {
				$maxPrice += $itemPrice * $val['FREE_QTY_KAR'];
			}
			if ($val['FREE_QTY_PAK'] > 0) {

				$r = $firstID -> EA_CARTON / $firstID -> EA_PACK;
				$s = explode("/", $unit);
				$pricePerUnit = $s[1];
				if ($pricePerUnit == "CAR") {
					$ratio = $firstID -> EA_CARTON;
				} else if ($pricePerUnit == "PAC") {
					$ratio = $firstID -> EA_PACK;
				}
				$priceUnit = $price / $ratio;
				$maxPrice += ($priceUnit) * $val['FREE_QTY_PAK'];
			}

			if ($val['FREE_QTY_EA'] > 0) {
				$r = $firstID -> EA_CARTON / $firstID -> EA_PACK;
				$s = explode("/", $unit);
				$pricePerUnit = $s[1];
				if ($pricePerUnit == "CAR") {
					$ratio = $firstID -> EA_CARTON;
				} else if ($pricePerUnit == "PAC") {
					$ratio = $firstID -> EA_PACK;
				}
				$priceUnit = $price / $ratio;
				$maxPrice += ($priceUnit) * $val['FREE_QTY_EA'];
			}

		}

		foreach ($productList as $l => $m) {
			$m -> $PRICE_COLUMN;
			$columnUnit = str_replace("_PRICE", "_UNIT", $PRICE_COLUMN);
			$saleUnit = $m -> $columnUnit;

			if ($saleUnit != "") {

				$s = explode("/", $saleUnit);

				$pricePerUnit = $s[1];
				if ($pricePerUnit == "CAR") {
					$ratio = $m -> EA_CARTON;
				} else if ($pricePerUnit == "PAC") {
					$ratio = $m -> EA_PACK;
				}

				$priceUnit = $m -> $PRICE_COLUMN / $ratio;

			}

			$p++;
		}

		$p++;
	}
}
?>



<script type="text/javascript">
	$(function() {

		$(".inputQty").keydown(function(e) {
			// Allow: backspace, delete, tab, escape, enter and .
			if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
			// Allow: Ctrl+A
			(e.keyCode == 65 && e.ctrlKey === true) ||
			// Allow: home, end, left, right, down, up
			(e.keyCode >= 35 && e.keyCode <= 40)) {
				// let it happen, don't do anything
				return;
			}
			// Ensure that it is a number and stop the keypress
			if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
				e.preventDefault();
			}
		});

		$('.inputQty').blur(function() {
			var v = $(this).val();
			if (v == "") {
				v = 0;
				$(this).val("0");
			}
			var p = $(this).attr("item-price");
			var number = parseFloat(v) * parseFloat(p);
			$(this).next('span').html(fixedNumber(number));
			allPrice = 0;
			$.each($(this).parents('.bodyinput').find('.resultPrice'), function(a, b) {
				var numPrice = $(b).html();
				numPrice = parseFloat(numPrice);
				allPrice += numPrice;
			});
			var promo = $(this).parents('.bodyinput').parent('table').find('.allPromoPrice');
			var maxPrice = promo.attr("max-price");
			promo.html(addCommas(allPrice));
			maxPrice = maxPrice.replace(",", "");
			maxPrice = parseFloat(maxPrice)

			console.log("allprice" + allPrice);
			console.log("max price" + maxPrice);
			promo.parents('tr').find('td').css("background", "white");
			if (allPrice > maxPrice) {
				promo.parents('tr').find('td').css("background", "red");
			}

			//.

		})

		$('#mySubmit,#mySubmit2').click(function() {

			if (!checkQty()) {
				alert("กรอกของแถมเกินมูลค่า");
				return false;
			}

		})
		/*
		$('.bodyinput').each(function(index, obj) {
		var $this = $(this);
		var maxKAR = $this.attr("data-max-KAR");
		var maxPAK = $this.attr("data-max-PAK");
		var maxEA = $this.attr("data-max-EA");
		$this.find('input[name="addKAR[]"]:eq(0)').val(maxKAR);
		$this.find('input[name="addPAK[]"]:eq(0)').val(maxPAK);
		$this.find('input[name="addEA[]"]:eq(0)').val(maxEA);

		});*/
		//$('#mySubmit,#mySubmit2').click();
	})
	function callOnPrice() {

	}

	function checkQty() {
		var process = true;
		$.each($('.allPromoPrice'), function(a, b) {
			var v = $(this).html();
			v = parseFloat(v);
			var maxPrice = $(this).attr("max-price")
			maxPrice = maxPrice.replace(",", "");
			var max = parseFloat(maxPrice);

			if (v > max) {
				process = false;
				return false;
			}
		})
		return process;

	}
</script>


<input type="hidden" name="code" value="yes"/>

<?
include 'order_head.php';
?>
<br />
<h2 class="headSection">รายการของแถมส่วนลด </h2>
<table>
	<tr>
		<td style="width:200px">รวมมูลค่าของแถมต้องไม่เกิน</td>
		<td style="width:80px" align="right"><?php echo number_format($maxPrice,2)?> &nbsp;</td>
		<td colspan="2">บาท</td>
	</tr>
	<?
	if($allDicount > 0 ){
	?>
	<tr>
		<td style="width:100px" >มูลค่าส่วนลดต้องไม่เกิน</td>
		<td align="right"><?php echo $allDicount ?>  &nbsp;</td>
		<td >บาท</td>
		<td ><input type="radio" class="getDis" name="includeDis" value="Y" > ให้ส่วนลด <input checked="checked" class="getDis" type="radio" name="includeDis" value="N"> ไม่ให้ส่วนลด</td>
	</tr>
	<?
	}
	?>
</table>




<h2 class="headSection">ค้นหาสินค้า</h2>
<div class="form-group">
	<label> รหัสสินค้า / หรือชือสินค้า </label>
	<input type="text" id="searchProduct" class="normal-input" class="inputText" name="keyword" value="" />
	<input type="hidden" name="promotionID" value="<?php echo $promotionID?>"/>
	<button id="searchd" type="button" class="btn-search">
		<i class="fa fa-search"></i> ค้นหาสินค้า
	</button>
</div>

<div id="resultTable" class="none">
		<form id="myForm" action="<?php echo $current?>updatecartPromotion" class="form-horizontal" role="form">		
		<div class="clear"></div>
		<br />
		<table class="myTable" style="width:100%">
			<tr>
				<th >รหัสสินค้า</th>
				<th >ชื่อสินค้า</th>
				<th >หน่วยขาย</th>
				<th >ราคาขาย</th>
				<th >คงเหลือ</th>
				
				<th class="qty">Carton</th>
				<th class="qty">Pack</th>
				<th class="qty">Ea</th>
				
			</tr>
			<tbody id="myBody">

			</tbody>
		</table>
		<div class="clear"></div>
		<br />
		<button type="submit">
			เพิ่มของแถม
		</button>
		
		
	</form>
</div>

<?
if($this->cart->total_items() > 0){
?>
<h2 class="headSection">รายการของแถมปัจจุบัน</h2>
<table cellpadding="6" cellspacing="1"  border="0" class="myTable">
<tr>
	<th style="width:10%">ลบ</th>
  <th style="width:40%">สินค้า</th>
  <th style="text-align:right;width:10%">ราคาต่อหน่วย</th>
  <th style="text-align:center;width:10%">หน่วย</th>
  <th style="text-align:center;width:20%">จำนวน</th>
  <th style="text-align:right;width:10%">ราคารวม</th>
</tr>

<?php $i = 1; ?>
<?
$pricePremium = 0;
?>
<?php foreach ($this->cart->contents() as $items): ?>

	<?
	$option = $this->cart->product_options($items['rowid']);
	

	$option = (array)$option;
	
	
	if(isset($option['ISPremium']) && $option['ISPremium']=="Yes" ){
		
		
	$pID = $option['MATNR'];
	$pName = $option['MAKTX'];
	$baseUnit = $option['BASE_UNIT'];
	if($baseUnit=="KAR"){
		$b = "ลัง";
	}else if($baseUnit=="PAK"){
		$b = "แพ็ก";
	}else {
		$b = "ชิ้น";
	}
	$pricePremium+=$items['subtotal'];
	?>

	<tr>
		<td style="width:10%" align="center">
			<a data-index="<?php echo  $items['rowid']?>" href="#" class="todelete"><img style="width:20px;height:20px;" src="<?php echo base_url()?>asset/images/Delete-32.png" /></a>
			
		</td>
	  <td style="width:40%"><?php echo $pID ?><br />
		<?php echo $pName ?></td>
		 <td style="text-align:right;width:60px">
	  	<div style="width:60px;float:right;float:right;"><?php echo $this->cart->format_number($items['price']); ?></div>
	  </td>
		<td style="width:20%;text-align: center;"><?php echo $b ?></td>
		<td style="width:10%;text-align: right;"><?php echo converUnit($items,$option);?></td>
	 
	 
	  <td style="text-align:right;width:90px">
	  	<div style="width:90px;float:right;"><?php echo $this->cart->format_number($items['subtotal']); ?></div>
	  </td>
	</tr>

<?php $i++; 
}
?>

<?php endforeach; ?>
<tr>
  <td colspan="4"> </td>
  <td class="right"><strong>ราคารวมต้องไม่เกิน</strong></td>
  <td class="right" style="text-align: right"><?php echo $this->cart->format_number($maxPrice); ?></td>
</tr>

<tr>
  <td colspan="4"> </td>
  <td class="right"><strong>ราคารวม</strong></td>
  <td class="right" style="text-align: right"><?php echo $this->cart->format_number($pricePremium); ?></td>
</tr>

</table>
<br />
<?
}
?>
<?
	$pricePremium = $this->cart->format_number($pricePremium); //$pricePremium ทศนิยม 4 ตำแหน่งทำให้มูลค่าของแถมมากกว่า
	if($maxPrice < $pricePremium){
	?>
		<div class="rowFrom rowWarning" style="padding:10px">
			<h2>มูลค่าของแถมมีมากกว่าที่ระบุ</h2>
			<p class="lead">กรุณาตรวจสอบจำนวนของสินค้า</p>
		</div>
	<?
	}else{
?>
<form  id="myPost" action="<?php echo $current?>tosummaryorder" method="post">
<a class="btn-default" href="<?php echo base_url()?>order/editorder/<?php echo $this -> session -> userdata("CORDERID"); ?>">
	<i class="fa fa-chevron-left"></i> ย้อนกลับ</a> | 
<button id="mySubmit" type="submit" class="btn-next">  ถัดไป <i class="fa fa-chevron-right"></i></button>
<input type="hidden" name="discount" value="<?php echo $allDicount?>" />
<input type="hidden" name="priceType" value="<?php echo $PRICE_COLUMN?>" />
<input type="hidden" name="getDiscount" value="N" />
<input type="hidden" name="priceTypeUnit" value="<?php echo $PRICE_COLUMN_UNIT?>" />
<input type="hidden" name="orderid" value="<?php echo $this->session->userdata("CORDERID")?>" />
</form>
<?
	}
?>
<script type="text/javascript">
	$(function(){
	/*
	$('#viewCart').click(function(){
		$('#myForm2').submit();
		
	})	*/
	
	$('.todelete').click(function(){
			var index = $(this).attr("data-index");
			var u = "<?php echo base_url()?>order/removeorder/";
			var d = {index:index};
			initCustom(u,d,function(data){
				if(data.flag){
					window.location.reload();
				}
			})
			return false;
	})
		
		
	$('.getDis').click(function(){
		
		$('input[name="getDiscount"]').val($(this).val())
	})
	initNormalForm(function(data){
			if(data.flag=="true"){
				alert("บันทึกข้อมูลเรียบร้อยแล้ว");
				window.location.reload();
			}
	})
	
	$('#searchd').click(function(){
		var pName = $('#searchProduct').val();
		initCustom('<?php echo $current?>seachproductPromotion',
			{	keyword:pName
				,'promotionID':'<?php echo $promotionID ?>'
				,'priceType':'<?php echo $PRICE_COLUMN ?>'
				,'priceTypeUnit':'<?php echo $PRICE_COLUMN_UNIT ?>'
			}
			,function(data){
				
				
			if(data.flag){
				var html = "";
				$.each(data.message,function(a,b){
					var stock  = b.STOCK;
					unit = "";
					var input1,input2,input3;
				
		var allQty = b.qty;
		//console.log("2");
		ratioEA = (b.EA_PACK / 1);
		if(b.EA_PACK!=0){
				
		
		
		ratioPack = (b.EA_CARTON / b.EA_PACK);
		currentCQty = Math.floor(allQty / b.EA_CARTON);
		
		
		if(currentCQty > 0 ){
			allQty = allQty - (currentCQty*b.EA_CARTON);
		}
		
		currentPQty = Math.floor(allQty / b.EA_PACK);;
		if(currentPQty > 0 ){
			allQty = allQty - (currentPQty*b.EA_PACK);
		}
		currentEQty = allQty;
		//console.log("5");
		
		if(b.BASE_UNIT=="EA"){
			unit = "ชิ้น";
			unit1 = '<input  style="width:100%" type="text" value="'+currentCQty+'" name="cQty[]" />';
			unit2 = '<select style="width:100%" name="pQty[]">';
			
			
			for(j=0;j<ratioPack;j++){
				select = (j==currentPQty)?' selected="selected"':"";
				unit2+='<option '+select+' value="'+j+'">'+j+'</option>';
			}
			unit2+='</select>'
			
			unit3 = '<select style="width:100%" name="eQty[]">';
			for(j=0;j<ratioEA;j++){
				select = (j==currentEQty)?' selected="selected"':"";
				unit3+='<option '+select+' value="'+j+'">'+j+'</option>';
			}
			unit3+='</select>'
		}else if(b.BASE_UNIT=="PAK"){
			unit = "แพ็ก";
			
			unit1 = '<input type="hidden" name="cQty[]" value="0" />';
			unit2 = '<input  style="width:40px" type="text" value="'+b.qty+'" name="pQty[]" />';
			unit3 = '<input  style="width:40px" type="text" value="'+b.qty+'" name="eQty[]" />';
		}else{
			unit = "ลัง";
			
			unit1 = '<input  style="width:40px" type="text" value="'+currentCQty+'" name="cQty[]" />';
			unit2 = '-<input type="hidden" name="pQty[]" value="0" />';
			unit3 = '-<input type="hidden" name="eQty[]" value="0" />';
			
		}
	html+='<tr>';
	html+='<td >'+b.MATNR+'</td>';
	html+='<td >'+b.MAKTX+'</td>';

			html+='<td align="right">'+unit+'</td>';
			
			html+='<td align="right">'+b.DisplayPrice+'</td>';
			html+='<td align="right">'+stock+'</td>';
	
			if(stock > 0 ){
				html+='<td class="qty"><input type="hidden" name="maxStock[]" value="'+stock+'" /><input type="hidden" name="price[]" value="'+b.CalPrice+'" />'+unit1+'</td>';
				html+='<td class="qty">'+unit2+'</td>';
				html+='<td class="qty">'+unit3+'<input type="hidden" name="qty[]" value="'+b.qty+'" /><input type="hidden" name="rowid[]" value="'+b.rowid+'" /><input type="hidden" name="pid[]" value="'+b.MATNR+'" /></td>';
			}else{
				html+='<td colspan="3">ไม่มีสินค้าใน Stock</td>';	
			}
	html+='</tr>'
	}
	})
	$('#myBody').html(html);
	$('#resultTable').show();
	}else{
	$('#resultTable').hide();
	$('#myBody').html("");
	alert(data.message);
	}
	});
	})
	
	})

</script>